import { useState, useRef, useEffect } from 'react'
import {
  Form,
  Input,
  Card,
  Breadcrumb,
  Space,
  Button,
  Radio,
  Upload,
  message,
  Modal,
} from 'antd'
import { Link, useHistory, useParams } from 'react-router-dom'
import { PlusOutlined } from '@ant-design/icons'
import { useDispatch } from 'react-redux'
import styles from './index.module.scss'
import Channel from '@/components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import {
  addArticle,
  getArticleInfo,
  editArticle,
} from '@/store/actions/article'

export default function Publish() {
  const { id } = useParams()
  const history = useHistory()
  const dispatch = useDispatch()
  const [fileList, setFileList] = useState([
    {
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },
  ])
  const [type, setType] = useState(1)
  const [isVisible, setIsVisible] = useState(false)
  const [preview, setPreview] = useState(false)
  const fileRef = useRef(fileList)
  const formRef = useRef(null)
  const add = async (draft, values) => {
    const images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const data = {
      ...values,
      cover: {
        type: type,
        images: images,
      },
    }
    if (id) {
      // !修改
      await dispatch(
        editArticle(draft, {
          ...data,
          id,
        })
      )
    } else {
      // !新增
      await dispatch(addArticle(draft, data))
    }
    message.success('添加文章成功')
    history.push('/home/article')
  }
  const onFinish = async (values) => {
    add(false, values)
  }
  const addDraft = async () => {
    const values = await formRef.current.validateFields()
    add(true, values)
  }
  const onChange = ({ fileList }) => {
    setFileList(fileList)
    fileRef.current = fileList
    formRef.current.validateFields(['type'])
  }
  const onTypeChange = (e) => {
    const count = e.target.value
    // 数量
    setType(count)
    // 从最终的结果里面截取需要的部分
    setFileList(fileRef.current.slice(0, count))
  }
  const onPreview = (file) => {
    setIsVisible(true)
    setPreview(file.url || file.response.data.url)
  }
  useEffect(() => {
    if (!id) return
    dispatch(getArticleInfo(id)).then((res) => {
      formRef.current.setFieldsValue({
        ...res,
        type: res.cover.type, // !#1 封面单选按钮的回显
      })
      setType(res.cover.type) // !#2 控制 type 的正确数值
      // !#3 图片的回显
      const list = res.cover.images.map((item) => ({
        url: item,
      }))
      setFileList(list)
      // !#4 图片仓库的初始化，不然切换的时候会有问题
      fileRef.current = list
    })
  }, [id, dispatch])
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator='>'>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          size='large'
          initialValues={{
            content: '',
            type,
          }}
          onFinish={onFinish}
          validateTrigger={['onBlur', 'onChange']}
          ref={formRef}
        >
          <Form.Item
            label='标题'
            name='title'
            rules={[
              {
                required: true,
                message: '标题不能为空',
              },
            ]}
          >
            <Input placeholder='请输入文章的标题' style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label='频道'
            name='channel_id'
            rules={[
              {
                required: true,
                message: '频道不能为空',
              },
            ]}
          >
            <Channel />
          </Form.Item>
          <Form.Item
            label='封面'
            name='type'
            rules={[
              {
                validator(_, value) {
                  // value => 表示选中的数量
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {type > 0 && (
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Upload
                listType='picture-card'
                fileList={fileList}
                action={`${process.env.REACT_APP_URL}upload`}
                name='image'
                onChange={onChange}
                maxCount={type}
                onPreview={onPreview}
              >
                {fileList.length < type && <PlusOutlined />}
              </Upload>
            </Form.Item>
          )}
          <Form.Item
            label='内容'
            name='content'
            rules={[
              {
                required: true,
                message: '内容不能为空',
              },
            ]}
          >
            <ReactQuill />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type='primary' htmlType='submit'>
                {id ? '编辑' : '发布'}文章
              </Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        width={800}
        title='图片预览'
        visible={isVisible}
        footer={null}
        onCancel={() => setIsVisible(false)}
      >
        <div style={{ textAlign: 'center' }}>
          <img src={preview} style={{ width: 600 }} alt='' />
        </div>
      </Modal>
    </div>
  )
}
